package com.study.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pojo.entity.MessageLogEntity;
import com.pojo.entity.MessageTaskEntity;
import com.pojo.req.MessageTaskReq;
import com.quartz.config.JobConstant;
import com.quartz.jobTask.JobExecuteContent;
import com.quartz.jobTask.MessageInfo;
import com.study.message.job.MessageJob;
import com.study.mapper.MessageLogMapper;
import com.study.mapper.MessageTaskMapper;
import com.study.service.IMessageTaskService;
import org.quartz.JobDataMap;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 消息发送任务 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-12-05
 */
@Service
public class MessageTaskServiceImpl extends ServiceImpl<MessageTaskMapper, MessageTaskEntity> implements IMessageTaskService {

    private final MessageJob messageJob;

    private final JobExecuteContent jobExecuteContent;

    private MessageLogMapper messageLogMapper;

    public MessageTaskServiceImpl(MessageJob messageJob,
                                  JobExecuteContent jobExecuteContent,
                                  MessageLogMapper messageLogMapper) {
        this.messageJob = messageJob;
        this.jobExecuteContent = jobExecuteContent;
        this.messageLogMapper = messageLogMapper;
    }


    /**
     *  异步消息发送
     * @param messageTaskReq
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void messageSend(MessageTaskReq messageTaskReq) {
        /**
         *  存储消息实例信息
         */
        MessageTaskEntity messageTaskEntity = new MessageTaskEntity();
        BeanUtils.copyProperties(messageTaskReq,messageTaskEntity);
        if (Objects.isNull(messageTaskEntity.getStartDate())){
            messageTaskEntity.setStartDate(LocalDateTime.now());
        }
        super.baseMapper.insert(messageTaskEntity);
        /**
         * 添加消息日志信息
         */
        MessageLogEntity messageLogEntity = new MessageLogEntity();
        messageLogEntity.setTaskId(messageTaskEntity.getId());
        messageLogEntity.setMessageType(messageTaskReq.getMessageType());
        messageLogEntity.setMeggageStatus(JobConstant.IMMEDIATELY);
        messageLogMapper.insert(messageLogEntity);

        // 创建 发送 Job 定时数据对象
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put(JobConstant.TASK_ID,messageTaskEntity.getId());
        jobDataMap.put(JobConstant.TOG_ID,messageLogEntity.getId());
        MessageInfo messageInfo = new MessageInfo();
        BeanUtils.copyProperties(messageTaskEntity,messageInfo);
        messageInfo.setCustomJob(messageJob);
        messageInfo.setTaskId(messageTaskEntity.getId());
        messageInfo.setJobDataMap(jobDataMap);
        jobExecuteContent.createJob(messageInfo);
    }
}
